%{
#include <stdio.h>
#include <malloc.h>		/* added by NPM */
/* #define DEBUG */
/* NPM: removed this extern char *calloc(); */

/*
 * Read the information at the beginning of dtd1.l for
 * more information about this program.
 */

/*
 * Structure used to create a linked list of entities including
 * their key and data.
 */
static struct entityDef {
    char *key;
    char *data;
    struct entityDef *next;		/* For table insertion */
    struct entityDef *prev;		/* For table insertion */
} *topEntList, *bottomEntList, *saveEntList;

/*
 * Structure used to create a linked list of the SGML markups
 * found in the dtd.  Currently only ENTITY and ATTLIST are supported.
 */
static struct SGMLitem {
    char *str;		/* Will change to include ENTITY and ATTLIST later */
    struct SGMLitem *next;
    struct SGMLitem *prev;		/* For table insertion */
} *topSGMLList, *bottomSGMLList, *saveSGMLList;

extern int yygetlineno();
void yyerror(char *s);

static void addEntTable(struct entityDef *new);
static char *LookupEnt(char *key);
static struct entityDef *newEntity(char *key, char *data);
static void DumpEntTable();
static void FreeEntTable();

static void addSGMLTable(struct SGMLitem *new);
static struct SGMLitem *newSGML(char *string);
static void DumpSGMLTable();

#define SGMLTYPE	1
#define ENTDEFTYPE	2
%}

%union {
    char *string;
    int option;
    struct entityDef *entitydef;
    struct SGMLitem *sgmlitem;
    int sgmltype;		/* SGMLTYPE or ENTDEFTYPE */
}

%token SGML COND ENTSTART QUOTE ELESTART ATTSTART
%token <string> WORD ENTITY
%token COMMENTEND

%type <string> words qstring word sgmlcontent sgmllist sgmlcontentitem 
%type <entitydef> entdef
%type <sgmlitem> sgml
%type <sgmltype> sgmllistitem

%%
top		: line
		    {
		    }
		| top line
		    {
		    }
		| error
		    {
			fprintf(stderr, "%d: syntax error\n", yygetlineno());
		    }
		;

line		: sgmllist
		| cond

sgmllist	: sgmllistitem
		    {
			/*
			 * First item in the list.
			 * We need to save the state of the entity table
			 * and the SGML list so we can back out our changes
			 * if we are in a conditional and it proves to be
			 * an IGNORE. This global hack does limit us to one
			 * level of depth on conditional SGMLs.
			 *
			 * Note that by now the first Entity or SGML 
			 * has been added to the list, so we have to
			 * use the previous when we save the state of that
			 * list.
			 */
			if (bottomEntList) {
			    if ($1 == ENTDEFTYPE)
				saveEntList = bottomEntList->prev;
			    else
				saveEntList = bottomEntList;
			}
			if (bottomSGMLList) {
			    if ($1 == SGMLTYPE)
				saveSGMLList = bottomSGMLList->prev;
			    else
				saveSGMLList = bottomSGMLList;
			}
		    }
		| sgmllist sgmllistitem

		;

sgmllistitem	: sgml
		    {
			/*
			 * We have a complete SGML statement.
			 * Save it in the SGML list (table).
			 */
			if ($1) {
#ifdef DEBUG
			    fprintf(stderr, "New SGML %s\n",
				    $1->str);
#endif
			    addSGMLTable($1);
			}
			$$ = SGMLTYPE;
		    }
		| entdef
		    {
			/*
			 * We have defined an entity.
			 * Save it in the Entity list (table).
			 */
			if ($1) {
#ifdef DEBUG
			    fprintf(stderr, "New Entity %s: %s\n",
				    $1->key,
				    $1->data);
#endif
			    addEntTable($1);
			}
			$$ = ENTDEFTYPE;
		    }
		| ENTITY
		    {
			/*
			 * There are cases in the dtd where we get lines like:
			 * 		%ISOlat1;
			 * in the dtd.  We just print a warning and ignore
			 * these lines.
			 */
			fprintf(stderr, "%d: Ignoring single line entity: %s\n",
				yygetlineno(),
				$1);
			$$ = 0;
		    }
		;

sgml		: ELESTART sgmlcontent sgmlend
		    {
			char *str = malloc(4096);

			sprintf(str, "<!ELEMENT %s>", $2);
			free ($2);
			$$ = newSGML(str);
		    }
		| ATTSTART sgmlcontent sgmlend
		    {
			char *str = malloc(4096);

			sprintf(str, "<!ATTLIST %s>", $2);
			free ($2);
			$$ = newSGML(str);
		    }
		| SGML sgmlend
		    {
			/* Empty sgml -- probably an eaten comment */
			$$ = 0;
			/*
			sprintf($$, "<!-- deleted comment -->");
			*/
		    }
		| SGML WORD sgmlcontent sgmlend
		    {
			char *str = malloc(4096);

			sprintf(str, "<!%s %s>", $2, $3);
			$$ = newSGML(str);
			fprintf(stderr, "Unknown SGML passed through: %s\n",
				$2);
			free ($2);
			free ($3);
		    }
		| SGML WORD error
		    {
			fprintf(stderr, "Unknown SGML ignored: %s\n", $2);
			free($2);
			$$ = 0;
		    }
		;

sgmlcontent	: sgmlcontentitem
		    {
			$$ = $1;
		    }
		| sgmlcontent sgmlcontentitem
		    {
			strcat($$, " ");
			strcat($$, $2);
			free($2);
		    }
		;

sgmlcontentitem	: words
		    {
			$$ = $1;
		    }
		| qstring
		    {
			$$ = $1;
		    }
		;

sgmlend		: '>'
		| COMMENTEND
		;
		
words		: word
		    {
			$$ = calloc(1, 4096);
			strcat($$, $1);
			free($1);
			/*
			fprintf(stderr, "Starting words: %s\n", $$);
			*/
		    }
		| words word
		    {
			$$ = $1;
			strcat($$, " ");
			strcat($$, $2);
			free($2);
			/*
			fprintf(stderr, "Adding to words: %s\n", $$);
			*/
		    }
		;

word		: WORD
		    {
			$$ = $1;
		    }
		| ENTITY
		    {
			char *ent = LookupEnt($1);
			if (ent == NULL) {
			    fprintf(stderr, "%d: Unknown Entity: %s\n",
				    yygetlineno(), $1);
			    $$ = calloc(1, 1);
			}
			else {
			    $$ = (char *)strdup(ent);
			}
		    }
		;

cond		: COND word '[' sgmllist ']' ']' '>'
		    {
			/*
			 * We have to read in the entire list before
			 * we evaluate the conditional.  Because of
			 * this, we may have added entities and SGMLS
			 * to the those lists which we want to get
			 * rid of.  That's what happens here.
			 */
			if (strcmp($2, "IGNORE") == 0) {
			    /* Reset the lists to ignore the contents */
			    if (saveEntList) {
				saveEntList->next = 0;	/* Lose data */
				bottomEntList = saveEntList;
			    }
			    /* else error XXX */

			    if (saveSGMLList) {
				saveSGMLList->next = 0;
				bottomSGMLList = saveSGMLList;
			    }
			    /* else error XXX */
			}
		    }
		;

entdef		: ENTSTART '%' WORD qstring '>'
		    {
			$$ = newEntity($3, $4);
		    }
		| ENTSTART '%' WORD qstring COMMENTEND
		    {
			$$ = newEntity($3, $4);
		    }
		| ENTSTART '%' WORD qstring error
		    {
			fprintf(stderr, "%d: incomplete entity: %s\n",
				yygetlineno(),
				$3);
			free($3);
			free($4);
			$$ = 0;
		    }
		| ENTSTART '%' WORD error
		    {
			fprintf(stderr, "%d: incomplete entity: %s\n",
				yygetlineno(),
				$3);
			free($3);
			$$ = 0;
		    }
		| ENTSTART '%' error
		    {
			fprintf(stderr, "%d: incomplete entity\n",
				yygetlineno());
			$$ = 0;
		    }
		| ENTSTART '%' WORD WORD qstring '>'
		    {
			$$ = newEntity($3, $5);
			free($4);
		    }
		| ENTSTART '%' WORD WORD qstring COMMENTEND
		    {
			fprintf(stderr, "%d: Ignoring entity %s\n",
				yygetlineno(),
				$3);
			free($3);
			free($4);
			free($5);
			$$ = 0;
		    }
		| ENTSTART WORD WORD qstring '>'
		    {
			fprintf(stderr, "%d: Ignoring entity %s\n",
				yygetlineno(),
				$3);
			free($2);
			free($3);
			free($4);
			$$ = 0;
		    }
		| ENTSTART WORD WORD qstring COMMENTEND
		    {
			fprintf(stderr, "%d: Ignoring entity %s\n",
				yygetlineno(),
				$2);
			free($2);
			free($3);
			free($4);
			$$ = 0;
		    }
		;

qstring		: QUOTE words QUOTE
		    {
			$$ = calloc(1, 4096);
			sprintf($$, "\"%s\"", $2);
			free ($2);
			/*
			fprintf(stderr, "Got qstring: %s\n", $$);
			*/
		    }
		| QUOTE QUOTE
		    {
			sprintf($$, "\"\"");
			/*
			fprintf(stderr, "Got qstring: %s\n", $$);
			*/
		    }
		| QUOTE words error
		    {
			fprintf(stderr, "%d: missing endquote\n", yygetlineno());
		    }
		| QUOTE error
		    {
			fprintf(stderr, "%d: incomplete quote\n", yygetlineno());
		    }
		;


%%

extern FILE *yyin;

main()
{
    while (!feof(yyin)) {
	yyparse();
    }
    /*
    DumpEntTable();
    */

    /*
     * DumpSGMLTable() writes out the SGML table which is
     * now cleaned up and processed.
     */
    DumpSGMLTable();
    FreeEntTable();
    exit(0);
}

void
yyerror(char *s)
{
    fprintf(stderr, "%d: %s\n", yygetlineno(), s);
}


/***************** Entities ******************/


/*
 * Add a new entity to the entity list.
 */
static void
addEntTable(struct entityDef *new)
{
    /* Only first reference gets added to the table */
    char *cp = LookupEnt(new->key);
    if (cp == NULL) {
	if (topEntList == 0) {
	    topEntList = new;
	    bottomEntList = new;
	}
	else {
	    bottomEntList->next = new;
	    new->prev = bottomEntList;
	    bottomEntList = new;
	}
    }
    else {

#ifdef DEBUG
	fprintf(stderr, "\tIgnoring New Entity %s: %s\n",
		new->key,
		new->data);
#endif /* DEBUG */

	free(new->key);
	free(new->data);
	free(new);
    }
}

/*
 * Lookup an entity in the entity list.
 * To avoid memory and freeing problems, we save the value
 * with the existing quote at the beginning.  We have to
 * avoid it when we return the entity value.
 */
static char *
LookupEnt(char *key)
{
    struct entityDef *cur = topEntList;
    while (cur) {
	if (strcmp(cur->key, key) == 0)
	    return (cur->data + 1);		/* Skip first " */
	cur = cur->next;
    }
    return (NULL);
}

/*
 * Create a new entity.
 */
static struct entityDef *
newEntity(char *key, char *data)
{
    struct entityDef *new = (struct entityDef *)malloc(sizeof(struct entityDef));

    new->key = key;
    new->data = data;
    new->next = 0;
    data[strlen(data) - 1] = 0;		/* Nuke last " */
    /*
    fprintf(stderr, "Creating entity: %s = %s\n", key, data);
    */
    return (new);
}

/*
 * Print out the entity table.  This is used only for debugging.
 */
static void
DumpEntTable()
{
    struct entityDef *cur = topEntList;
    fprintf(stderr, "\nEntity Table (0x%x):\n", topEntList);
    while (cur) {
	fprintf(stderr, "%%%s : %s\n", cur->key, cur->data + 1);
	cur = cur->next;
    }
}

/*
 * Clean up the entity table.
 */
static void
FreeEntTable()
{
    struct entityDef *cur = topEntList;
    while (cur) {
	struct entityDef *save = cur->next;
	
	free(cur->key);
	free(cur->data);
	free(cur);
	cur = save;
    }
    topEntList = 0;
}

/***************** SGML ******************/

/*
 * Add a new SGML markup to the SGML list.
 */
static void
addSGMLTable(struct SGMLitem *new)
{
    if (topSGMLList == 0) {
	topSGMLList = new;
	bottomSGMLList = new;
    }
    else {
	bottomSGMLList->next = new;
	new->prev = bottomSGMLList;
	bottomSGMLList = new;
    }
}

/*
 * Create a new data structure for the SGML markup.
 */
static struct SGMLitem *
newSGML(char *string)
{
    struct SGMLitem *new = (struct SGMLitem *)malloc(sizeof(struct SGMLitem));

    new->str = string;
    new->next = 0;
    /*
    fprintf(stderr, "Creating SGML: %s\n", string);
    */
    return (new);
}

/*
 * Write out the SGML table.  Note that the strings in the SGML
 * list are of the standard form:
 *	<blah foo1 foo2 ... >
 * so they can be written out directly.
 */
static void
DumpSGMLTable()
{
    struct SGMLitem *cur = topSGMLList;

    while (cur) {
	fprintf(stdout, "%s\n", cur->str);
	cur = cur->next;
    }
}

